package com.zksite.nator.processor.http;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zksite.nator.common.container.ChannelContainer;
import com.zksite.nator.common.processor.RequestProcessor;
import com.zksite.nator.common.util.IdGen;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.ReferenceCountUtil;

/**
 * @author hanjieHu
 *
 */
@Component("httpForwardProcessor")
public class HttpForwardProcessor implements RequestProcessor {

	private static final Logger LOGGER = LoggerFactory.getLogger(HttpForwardProcessor.class);

	@Resource(name = "defaultClientContainer")
	private ChannelContainer clientContainer;

	@Autowired
	private IdGen idGen;

	@Resource(name = "sessionContainer")
	private ChannelContainer sessionContainer;

	@Override
	public boolean process(ChannelHandlerContext ctx, Object msg) {
		if (msg instanceof FullHttpRequest) {
			FullHttpRequest request = (FullHttpRequest) msg;
			HttpHeaders headers = request.headers();
			String host = headers.get("host");
			if (host == null) {
				ReferenceCountUtil.release(msg);
				return false;
			}
			if (host.indexOf(":") != -1) {
				host = host.split(":")[0].trim();
			}
			Channel channel = clientContainer.get(host);
			if (channel == null) {
				byte[] content = "404".getBytes();
				HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND,
						Unpooled.wrappedBuffer(content));
				response.headers().add("Content-Length", content.length);
				ctx.writeAndFlush(response);
				ReferenceCountUtil.release(msg);
				return false;
			}
			String sessionId = idGen.getId();
			headers.add("forwardid", sessionId);
			if (channel.isActive()) {
				channel.writeAndFlush(msg);
				sessionContainer.put(sessionId, ctx.channel());
				LOGGER.info("send request message finsh");
			}
		}
		return false;
	}

}
